using System.GunSystem;
using Command;
using QFramework;
using Query;

namespace ViewController.Gameplay
{
    public class Gun : ShootingEditor2DController
    {
        private Bullet _bullet;

        private GunInfo _gunInfo;

        private int _maxBulletCount;

        private void Awake()
        {
            _bullet = transform.Find("Bullet").GetComponent<Bullet>();

            _gunInfo = this.GetSystem<IGunSystem>().CurrentGun;

            _maxBulletCount = this.SendQuery(new MaxBulletCountQuery(_gunInfo.Name.Value));
        }

        private void OnDestroy()
        {
            _gunInfo = null;
        }

        public void Shoot()
        {
            if (_gunInfo.BulletCountInGun.Value > 0 && _gunInfo.GunState.Value == GunState.Idle)
            {
                var t = _bullet.transform;
                var bullet = Instantiate(t, t.position, t.rotation);

                // 统一缩放值
                bullet.transform.localScale = _bullet.transform.lossyScale;
                bullet.gameObject.SetActive(true);

                this.SendCommand<ShootCommand>();
            }
        }

        public void Reload()
        {
            if (_gunInfo.BulletCountInGun.Value < _maxBulletCount && _gunInfo.BulletCountOutGun.Value > 0 &&
                _gunInfo.GunState.Value == GunState.Idle)
                this.SendCommand<ReloadCommand>();
        }
    }
}